<template>
  <div class="shop-index">
    <!-- 查询条件区域 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <div>
        <el-form-item label="店铺名">
          <el-select v-model="queryForm.shopId" clearable style="width: 200px" placeholder="请选择店铺名">
            <el-option
              v-for="shop in allShop"
              :key="shop.shopId"
              :label="shop.shopName"
              :value="shop.shopId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="药品名">
          <el-input v-model="queryForm.medicineName" placeholder="请输入药品名"></el-input>
        </el-form-item>
        <el-form-item label="供应商名">
          <el-select v-model="queryForm.supplierId" clearable style="width: 200px" placeholder="请选择供应商名">
            <el-option
              v-for="supplier in allSupplier"
              :key="supplier.supplierId"
              :label="supplier.supplierName"
              :value="supplier.supplierId"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="分类">
        <div style="display: flex;flex-direction: column">
          <div style="display: flex; flex-direction: row; justify-content: flex-start;">
            <el-tag
                v-for="category in level.firstDate"
                :key="category.categoryId"
                :type="level.firstLevel === category.categoryId ? 'primary' : 'info'"
                @click="handleCategoryClick(category)"
                style="margin-right: 10px;"
            >
              {{ category.categoryName }}
            </el-tag>
          </div>
          <div style="display: flex; flex-direction: row; justify-content: flex-start;margin-top: 5px;">
            <el-tag
                v-for="category in level.secondDate"
                :key="category.categoryId"
                :type="level.secondLevel === category.categoryId ? 'primary' : 'info'"
                @click="handleCategoryClickSecond(category)"
            >
              {{ category.categoryName }}
            </el-tag>
          </div>
          <div style="display: flex; flex-direction: row; justify-content: flex-start;margin-top: 5px;">
            <el-tag
                v-for="category in level.thirdDate"
                :key="category.categoryId"
                :type="level.thirdLevel === category.categoryId ? 'primary' : 'info'"
                @click="handleCategoryClickThird(category)"
            >
              {{ category.categoryName }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
  <div style="width: 100%; height: auto">
    <!-- 药品展示卡片 -->
    <div class="medicine-grid" v-if="medicines.length > 0">
      <el-card v-for="medicine in medicines" :key="medicine.medicineId" class="medicine-card" shadow="hover" @click="toDerail(medicine.medicineId)">
        <div class="medicine-info">
          <el-image
            :src="medicine.medicineImg"
            style="width: 100px; height: 100px"
            fit="cover"
          />
          <h3>{{ medicine.medicineName }}</h3>
          <div class="price-point">
            <span class="price">价格: ¥{{ medicine.price }}</span>
            <span class="point">积分: {{ medicine.point }}</span>
          </div>
          <p>库存: {{ medicine.stockQuantity }}</p>
        </div>
      </el-card>
    </div>
    <div v-else class="no-medicines">
      <el-empty description="暂无药品"></el-empty>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { fetchSecondLevel, fetchThirdLevel, getAllFirstLevel } from "@/api/drugCategory";
import { searchMedicine } from "@/api/drug";
import { getAllSupplier } from "@/api/supplier";
import { getAllShop } from "@/api/shop";
import { useRouter } from 'vue-router'
const router = useRouter();
const queryForm = ref({
  shopId: '',
  medicineName: '',
  supplierId: ''
});

const level = reactive({
  firstLevel: '',
  firstDate: [
    {
      "categoryId": '',
      "categoryName": "全部",
      "parentId": null,
      "grandParentId": null
    }
  ],
  secondLevel: '',
  secondDate: [],
  thirdLevel: '',
  thirdDate: []
});
const allSupplier = ref([]);
const allShop = ref([]);

const medicines = ref([]);

const onQuery = async () => {
  // 处理查询逻辑
  console.log('查询条件:', queryForm.value);
  await searchMedicine({
    shopId: queryForm.value.shopId || null,
    medicineName: queryForm.value.medicineName || '',
    supplierId: queryForm.value.supplierId || null,
    categoryId: level.thirdLevel || null
  }).then((res) => {
    console.log("查询结果，",res)
    medicines.value = res.data.data;
  });
};

// 点击第一级分类
const handleCategoryClick = (category) => {
  if (category.categoryId === ''){
    // 获取所有药品
    level.secondLevel = '';
    level.secondDate = [];
    level.thirdDate = [];
    level.thirdLevel = '';
    onQuery()

  }else {
    level.firstLevel = category.categoryId;
    fetchSecondLevel({
      parentId: category.categoryId,
    }).then((res) => {
      level.secondDate = res.data.data;
    });
    level.secondLevel = '';
    level.thirdDate = [];
    level.thirdLevel = '';
  }

};

// 点击第二级分类
const handleCategoryClickSecond = async (category) => {
  level.secondLevel = category.categoryId;
  await fetchThirdLevel({
    parentId: category.categoryId,
    grandParentId: level.firstLevel
  }).then((res) => {
    level.thirdDate = res.data.data;
  });
};

// 点击第三级分类
const handleCategoryClickThird = (category) => {
  level.thirdLevel = category.categoryId;
  console.log(level);
  // 结合查询条件，进行查询
  onQuery();
};

watch(queryForm, (newVal) => {
  console.log('参数值变动',newVal);
  onQuery();
}, { deep: true });

onMounted(() => {
  // 查询第一级分类
  console.log('查询第一级分类');
  getAllFirstLevel().then((res) => {
    // 遍历res.data.data，将数据push到level.firstDate
    res.data.data.forEach((item) => {
      level.firstDate.push(item);
    });
    // level.firstDate = res.data.data;
  });
  // 获取店铺
  console.log('获取店铺');
  getAllShop().then((res) => {
    console.log('店铺', res.data.data);
    allShop.value = res.data.data;
  });
  // 获取供应商
  console.log('获取供应商');
  getAllSupplier().then((res) => {
    console.log('供应商', res.data.data);
    allSupplier.value = res.data.data;
  });
  onQuery()
});
const toDerail = (medicine) => {
  console.log('跳转',medicine);

  router.push({ path: '/productDetail', query: { medicineId:medicine } })
}
</script>

<style scoped>
.shop-index {
  padding: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  height: auto;
}

.medicine-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.medicine-card {
  transition: transform 0.2s;
}

.medicine-card:hover {
  transform: scale(1.05);
}

.medicine-info {
  padding: 10px;
}

.medicine-info h3 {
  margin: 0 0 10px 0;
}

.medicine-info p {
  margin: 5px 0;
}

.medicine-info p:last-child {
  font-weight: bold;
  color: #ff4d4f;
}

.price-point {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.price, .point {
  font-size: 16px;
}

.price {
  color: #ff5000;
}

.point {
  color: #409EFF;
}
</style>